import {handleIsJSON} from "@/utils/utils";

let tokenKey = "token"
function getToken (){
    return getLocalStorage(tokenKey)
}
function setToken(val){
    return  setLocalStorage(val,tokenKey)
}
function removeToken() {
    removeLocalStorage(tokenKey)
}

function getLocalStorage(key:string) {
    if(!localStorage.getItem(key))return "";
    if(handleIsJSON(localStorage.getItem(key))){
        // @ts-ignore
        let storageData = JSON.parse(localStorage.getItem(key))
        let {expire,data,time} = storageData
        if(time+expire>Date.now()){
            return data;
        }else{
            removeLocalStorage(key)
            return ""
        }
    }else{
        removeLocalStorage(key)
        return ""
    }
}
// /**
//  *
//  * @param key           存储 键
//  * @param data          存储 值
//  * @param expire        过期时间
//  */
function setLocalStorage(key:string,data:string|number,expire:number=72000000) {
    let obj = {
        data,
        time:Date.now(),
        expire
    }
    localStorage.setItem(key,JSON.stringify(obj))
}
function removeLocalStorage(key:string) {
    localStorage.removeItem(key);
}

export {
    getToken,
    setToken,
    removeToken
}